package cn.edu.gzhu.workOrderManagement.intercepter;

import cn.edu.gzhu.workOrderManagement.constants.MessageConstant;
import cn.edu.gzhu.workOrderManagement.enumeration.UserAuthorityEnum;
import cn.edu.gzhu.workOrderManagement.enumeration.WorkOrderProcessingStatusEnum;
import cn.edu.gzhu.workOrderManagement.mapper.UserMapper;
import cn.edu.gzhu.workOrderManagement.mapper.WorkOrderMapper;
import cn.edu.gzhu.workOrderManagement.pojo.dto.workOrder.WorkOrderUpdateDto;
import cn.edu.gzhu.workOrderManagement.pojo.entity.User;
import cn.edu.gzhu.workOrderManagement.pojo.entity.WorkOrder;
import cn.edu.gzhu.workOrderManagement.util.ResponseUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.stream.Collectors;

@Component
@Slf4j
public class WorkOrderUpdateInterceptor implements HandlerInterceptor {
    @Autowired
    WorkOrderMapper workOrderMapper;
    @Autowired
    UserMapper userMapper;
    //工单的当前处理者才可以更新工单
    //只有主管可以转单
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
        String body = request.getReader().lines().collect(Collectors.joining(System.lineSeparator()));
       //获取Dto
        WorkOrderUpdateDto workOrderUpdateDto = JSONUtil.toBean(body, WorkOrderUpdateDto.class);
        if (workOrderUpdateDto == null||workOrderUpdateDto.getUuid()==null) {
            ResponseUtil.failResponse(response, MessageConstant.PARAMETER_ERROR);
            return false;
        }
        //获取操作人信息
        Claims claims = (Claims) request.getAttribute("claims");
        String username = claims.get("username").toString();
        User opUser = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getUsername, username));

        //如果不是主管则不能转单
        if (workOrderUpdateDto.getNeedsReassignment()&& !UserAuthorityEnum.BRANCH_SUPERVISOR.equals(opUser.getAuthority())){
            ResponseUtil.failResponse(response, MessageConstant.PERMISSION_DENIED);
            return false;
        }

        //获取工单信息，不是处理者不能操作
        WorkOrder targetWorkOrder = workOrderMapper.selectOne(new LambdaQueryWrapper<WorkOrder>().eq(WorkOrder::getUuid, workOrderUpdateDto.getUuid()));
        if (targetWorkOrder==null){
            ResponseUtil.failResponse(response, MessageConstant.PARAMETER_ERROR);
            return false;
        }
       return validateUpdate(opUser,targetWorkOrder);

    }
    //可以操作相应的权限，和处理员可以操作分配到主管阶段且 teamMember为自己的工单
   private  Boolean validateUpdate( User user,WorkOrder targetWorkOrder){
       WorkOrderProcessingStatusEnum processingStatus = targetWorkOrder.getProcessingStatus();
       UserAuthorityEnum needAuthority = WorkOrderProcessingStatusEnum.getAuthorityEnum(targetWorkOrder);
       if (needAuthority==null){
           return false;
       }
       //如果是操作人就是目标工单teamMember的值,且已经转单，那么放行
       if (targetWorkOrder.getIsReassignment()&&targetWorkOrder.getTeamMember().equals(user.getUsername())){
           return true;
       }
       //如果不是本级权限处理的，拦截
       if (!needAuthority.equals(user.getAuthority())){
           return false;
       }
       //分公司检查是否是本分公司的
       if (user.getAuthority().getAuthority()>UserAuthorityEnum.HEAD_AUDITORS.getAuthority()){
           if (!targetWorkOrder.getBranchName().equals(user.getOrganization())){
               return false;
           }
       }

       return true;
   }
}
